const express = require('express')

const multer  = require('multer')


const  {writeFileSync} = require('fs')

const {resolve} = require('path')

/* 引入对post请求所需要的解析 */

const bodyparser = require('body-parser');

/* 引入con nect-multiparty模块 用来解析表单formdata数据的;否则body中娶不到数据 */
const multipart = require('connect-multiparty');

const app = express();

const ststus = {
     '200': '成功',
     '400': '请求错误',
     '401': '未授权',
     '403': '禁止访问',
     '404': '网址错误',
     '500': '服务器错误',
     '503': '服务器维护',
     '504': '服务器超时',
     '505': 'HTTP版本不支持',
     '506': '服务器不支持协议转换',
     '507': '存储空间不足',
     '508': '服务器配置错误',
     '509': '超出带宽限制',
}

class RequestStatus{
     code; 
     msg;
     data;
     constructor(code,msg,data) {
         this.code = code
         this.msg = msg || '未知错误'
         this.data = data || {}
     }
     getMsg() {
        let msgs = {
            msg:  this.msg ? `${this.msg}${ststus[this.code]}` : ststus[this.code],
            code: this.code,
            data:this.data
        }
        return msgs
     }
}


app.all("*", function(req, res, next) {
    //设置允许跨域的header
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", ["Content-Type","Accept","ext","x-ext"]);
   res.header("Access-Control-Allow-Methods", ["POST","GET"]);
   next()
})


/*中间件注册对请求体的对象的处理 */
// app.use(bodyparser.json({limit:'100mb'})); 
// app.use(bodyparser.urlencoded({extended: true}));
app.use(multipart());




const Stroge = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads')
    },
    filename: function (req, file, cb) {
        const ext = file.originalname.split('.')[1];
        cb(null, Date.now() + '.' + ext)
    }
})

const upload =  multer({storage: Stroge})

/*content-type  multipart/form-data  */
app.post('/file', upload.single('file'),function(req, res,error) {
        if(req.file) {
           res.send(new  RequestStatus(200,'formdata文件').getMsg()) 
        } else {
             res.send(new  RequestStatus(400,'formdata文件').getMsg()) 
        }
  })
  /*base64文件上传方式*/
  app.post('/base64',function(req, res) {
    const {file,ext} = req.body;
    const binaryData = Buffer.from(file, 'base64');
    try {
        writeFileSync(resolve(__dirname+ `/uploads/${Date.now()}.${ext}`)  ,binaryData,'binary')
        res.send(new  RequestStatus(200,'base64文件').getMsg()) 
    } catch (error) {
        res.send(new  RequestStatus(400,'base64文件').getMsg()) 
    }
  
})

app.post('/binary',(req,res)=> {
    let ext = req.headers['x-ext']

    const buffers = []

    req.on('data', (chunk) => {
        buffers.push(chunk)
    })

    req.on('end', () => {
        const binaryData = Buffer.concat(buffers)
        try {
            writeFileSync(resolve(__dirname+ `/uploads/${Date.now()}.${ext}`)  ,binaryData,'binary')
            res.send(new  RequestStatus(200,'binary文件').getMsg()) 
        }catch (error) {
            res.send(new  RequestStatus(400,'binary文件').getMsg()) 

        }
    })
})

  app.post('/testformdata',(req,res)=> {
       console.log(req.body)
       res.send(req.body)
  })

  app.get('/getUsers',(req,res)=> {
    //  console.log(req.query)
    res.send('<h1>jjjj66</h1>')    

 
})
  

app.listen(8080, () => {
    console.log('Server is running on port 8080')
})